package org.abacus.dbtojava;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactoryProperties implements BeanFactory {
	private static final Map<String, BeanFactory> beanFactorys = new HashMap<String, BeanFactory>();
	private Properties props;

	private BeanFactoryProperties(String arg0) {
		super();
		props = new Properties();
		InputStream inStream = BeanFactoryProperties.class.getResourceAsStream("/" + arg0);
		try {
			props.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static synchronized BeanFactory getInstance(String arg0) {
		BeanFactory beanFactory = beanFactorys.get(arg0);
		if (null == beanFactory) {
			beanFactory = new BeanFactoryProperties(arg0);
			beanFactorys.put(arg0, beanFactory);
		}
		return beanFactory;

	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T createBean(String arg0, Class<T> arg1) {
		T t = null;
		Object value = props.get(arg0);
		if (null == value) {
			t = this.newInstance(arg1);
		}
		if (null != t) {
			return t;
		}
		try {
			Class<T> c = (Class<T>) Class.forName(value.toString());
			t = this.newInstance(c);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		if (null == t) {
			t = this.newInstance(arg1);
		}
		return t;
	}

	private <T> T newInstance(Class<T> arg1) {
		if (null == arg1) {
			return null;
		}
		try {
			return arg1.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public <T> T createBean(Class<T> arg0) {
		if (null == arg0) {
			return null;
		}
		return createBean(arg0.getName(), arg0);
	}

}
